<?php

namespace app\student\controller;

use app\student\security\StuCheck as StuCheckLogic;
use app\student\security\Auth as AuthLogic;
use think\Controller;
use think\Loader;
use think\Session;
use app\student\model\Login as LoginModel;
use app\student\model\Token as TokenModel;

class Login extends Controller
{
    /**
     * 登录界面显示，自动登录
     * @access public
     * @return mixed 返回登录视图
     */
    public function login()
    {
        //检测学生登录情况
        $stuCheck=new StuCheckLogic();
        if($stuCheck->check()==1){
            //成功跳转到主页
            $this->assign('config',getSrvConfig());
            return $this->fetch('index/index');
        }else{
            //失败跳转到登陆界面
            return $this->fetch('login/login');
        }
    }

    /**
     * 学生注销功能
     * @access public
     * @return mixed 返回登录视图
     */
    public function logout()
    {
        //清除Session
        Session::clear();
        return $this->fetch('login');
    }

    /**
     * 学生登录功能
     * @access public
     * @param string $username 学号
     * @param string $password 密码
     * @return integer 返回执行代码
     */
    public function do_login($username = '', $password = '')
    {
        //序列化用户登录信息
        $data = [
            'username' => $username,
            'password' => $password,
        ];

        //实例化验证类
        $validate = Loader::validate('Login');
        //验证教师输入的登录信息
        if ($validate->check($data)) {
            //实例化登录数据表模型
            $login = new LoginModel();
            //定义查询条件
            $condition = [
                'stuUsername' => $username,
                'stuPassword' => $password,
            ];
            //验证用户
            if ($login::where($condition)->find()) {
                //获取ip地址，服务器时间
                $ip = $this->getClientIp();
                $time = date('y-m-d h:i:s', time());
                //生成token，SHA256(工号,密码,客户端ip,服务器时间)
                $token = hash('sha256', $username . $password . $ip . $time);
                //定义需要写入的登陆信息
                $login['stuUsername'] = $username;
                $login['stuToken'] = $token;
                $login['stuClientIp'] = $ip;
                $login['CreateTime'] = $time;
                //储存登陆信息
                if ($login->isUpdate(true)->save()) {
                    $result['stuToken'] = $token;
                    $result['stuClientIp'] = $ip;
                    $result['CreateTime'] = $time;
                    //实例化Token信息视图
                    $tchToken = new TokenModel();
                    //定义需要查询的字段
                    $field = 'stuUsername,stuName,stuClass,stuMajorName,CreateTime,stuClientIp,stuToken';
                    if ($result = $tchToken::where($condition)->field($field)->find()) {
                        $auth=new AuthLogic();
                        $result['stuGroup']=$auth->getGroups($username);
                        //token写入session
                        Session::set('token', $result);
                        return 1;
                    } else {
                        return "生成会话失败，请联系网站管理员";
                    }
                } else {
                    return "生成令牌失败，请联系网站管理员";
                }
            } else {
                return "用户名或密码错误";
            }
        } else {
            return $validate->getError();
        }
    }

    /**
     * 获取客户端IP地址
     * @access private
     * @return string 返回客户端IP地址
     */
    private function getClientIp()
    {
        global $ip;
        if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else $ip = "Unknow IP";
        return $ip;
    }
}